const readline = require('readline');
const fs = require('fs');
const path = require('path');

/** 当前文件地址 */
const SRC_PATH = path.resolve(__dirname, '../src');

/** 模版路径 */
const TEMPLATE_PATH = path.resolve(__dirname, '../01-template');

/** 模版路径 - js */
const TEMPLATE_PATH_JS = path.resolve(TEMPLATE_PATH, '01-js');

class Auto {
  inputInfo = {
    title: '',
    url: '',
  };

  constructor() {
    this.getUserInput().then(() => {
      this.createFile();
    });
  }

  initReadLine() {
    // 创建readline接口实例
    const rl = readline.createInterface({
      input: process.stdin, // 控制台输入
      output: process.stdout, // 控制台输出
    });

    this.rl = rl;
  }

  /** 获取用户输入内容 */
  async getUserInput() {
    this.initReadLine();

    await this.getUserInputTitle();

    await this.getUserInputUrl();

    // await this.getUserInputContent();

    // 关闭readline接口
    this.rl.close();

    const info = `[title]: ${this.inputInfo.title}\n[url: ${this.inputInfo.url}`;
    console.log(info);

    return Promise.resolve(info);
  }

  /** 创建文件 */
  async createFile() {
    const { title, url } = this.inputInfo;

    const dirPath = path.join(SRC_PATH, title);

    if (fs.existsSync(dirPath)) {
      console.error(`[目录已存在]: ${dirPath}\n`);
      throw new Error(`[目录已存在]: ${dirPath}`);
    }

    // 创建目录
    fs.mkdirSync(dirPath);

    await copyUnitTestFile();

    copyIndexFile(title, url);

    console.log(`[创建目录成功]: ${dirPath}`);

    /** 复制单元测试文件 */
    function copyUnitTestFile() {
      return new Promise((resolve, reject) => {
        const fileName = 'test.js';

        const srcFilePath = path.join(TEMPLATE_PATH_JS, fileName);

        const destFilePath = path.join(dirPath, fileName);

        // 异步复制文件
        fs.copyFile(srcFilePath, destFilePath, (err) => {
          if (err) {
            console.error('复制文件时发生错误:', err);
            reject(err);
          } else {
            console.log('[文件复制成功]' + destFilePath);
            resolve();
          }
        });
      });
    }

    /** 复制 - index.js */
    function copyIndexFile(title, url) {
      const srcFilePath = path.join(TEMPLATE_PATH_JS, 'index.js');
      const destFilePath = path.join(dirPath, 'index.js');

      let res = fs.readFileSync(srcFilePath, 'utf-8');
      res = res.replaceAll('$title', title).replaceAll('$url', url);

      fs.writeFileSync(destFilePath, res, 'utf-8');
    }
  }

  /** 获取标题 */
  getUserInputTitle() {
    return new Promise((resolve, rejects) => {
      this.rl.question('请输入题目标题（如：2. 两数相加）: \n', (answer) => {
        answer = answer.trim();
        if (!answer.length) return console.log('请输入正确的标题');

        this.inputInfo.title = answer;

        console.log('\n\n');
        resolve();
      });
    });
  }

  /** 获取url */
  getUserInputUrl() {
    return new Promise((resolve, rejects) => {
      this.rl.question('请输入题目url: \n', (answer) => {
        answer = answer.trim();
        if (!answer.length) return console.log('请输入正确的url');

        this.inputInfo.url = answer;

        console.log('\n\n');
        resolve();
      });
    });
  }

  /** 获取题目内容 */
  getUserInputContent() {
    return new Promise((resolve, rejects) => {
      this.rl.question('请输入题目内容: \n', (answer) => {
        answer = answer.trim();
        if (!answer.length) return console.log('请输入正确的题目内容');

        console.log('\n\n');
        resolve();
      });
    });
  }
}

new Auto();
